// food-management.js
const app = getApp();

Page({
  data: {
    foods: [],
    filteredFoods: [],
    activeTab: 'all',
    searchKeyword: '',
    showAddModal: false,
    showDetailModal: false,
    currentFood: {},
    totalFoods: 0,
    expiringSoon: 0,
    foodCategories: 0,
    categories: ['蔬菜', '水果', '肉类', '主食', '调料', '其他'],
    units: ['个', '斤', '千克', '克', '袋', '盒', '瓶'],
    selectedCategory: '',
    selectedUnit: '',
    today: '',
    selectedDate: '',
    imagePreview: ''
  },

  onLoad: function() {
    // 设置当前日期为今天
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    this.setData({
      today: `${year}-${month}-${day}`
    });
    
    // 加载食材数据
    this.loadFoods();
  },

  onShow: function() {
    // 页面显示时重新加载数据
    this.loadFoods();
  },

  // 加载食材数据
  loadFoods: function() {
    // 这里应该调用API获取数据，现在使用模拟数据
    const mockData = [
      {
        id: 1,
        name: '西红柿',
        category: '蔬菜',
        quantity: 5,
        unit: '个',
        expiryDate: '2023-09-20',
        location: '冰箱',
        imageUrl: '../../images/tomato.png',
        status: 'normal'
      },
      {
        id: 2,
        name: '鸡胸肉',
        category: '肉类',
        quantity: 0.5,
        unit: '千克',
        expiryDate: '2023-09-16',
        location: '冰箱',
        imageUrl: '../../images/chicken.png',
        status: 'warning'
      },
      {
        id: 3,
        name: '苹果',
        category: '水果',
        quantity: 8,
        unit: '个',
        expiryDate: '2023-09-25',
        location: '橱柜',
        imageUrl: '../../images/apple.png',
        status: 'normal'
      },
      {
        id: 4,
        name: '大米',
        category: '主食',
        quantity: 5,
        unit: '千克',
        expiryDate: '2024-01-01',
        location: '橱柜',
        imageUrl: '../../images/rice.png',
        status: 'normal'
      }
    ];
    
    this.setData({
      foods: mockData
    });
    
    // 筛选食材
    this.filterFoods();
    
    // 更新统计数据
    this.updateStats();
  },

  // 筛选食材
  filterFoods: function() {
    let filtered = this.data.foods;
    
    // 按分类筛选
    if (this.data.activeTab !== 'all') {
      const categoryMap = {
        'vegetable': '蔬菜',
        'fruit': '水果',
        'meat': '肉类',
        'grain': '主食'
      };
      const category = categoryMap[this.data.activeTab];
      filtered = filtered.filter(food => food.category === category);
    }
    
    // 按关键词搜索
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase();
      filtered = filtered.filter(food => 
        food.name.toLowerCase().includes(keyword) ||
        food.category.toLowerCase().includes(keyword)
      );
    }
    
    this.setData({
      filteredFoods: filtered
    });
  },

  // 更新统计数据
  updateStats: function() {
    const total = this.data.foods.length;
    const expiring = this.data.foods.filter(food => food.status === 'warning' || food.status === 'expired').length;
    const categories = new Set(this.data.foods.map(food => food.category));
    
    this.setData({
      totalFoods: total,
      expiringSoon: expiring,
      foodCategories: categories.size
    });
  },

  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.filterFoods();
  },

  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
    this.filterFoods();
  },

  // 显示添加食材模态框
  showAddFoodModal: function() {
    this.setData({
      showAddModal: true,
      selectedCategory: '',
      selectedUnit: '',
      selectedDate: '',
      imagePreview: ''
    });
  },

  // 隐藏添加食材模态框
  hideAddFoodModal: function() {
    this.setData({
      showAddModal: false
    });
  },

  // 显示食材详情
  showFoodDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    const food = this.data.foods.find(f => f.id === id);
    this.setData({
      showDetailModal: true,
      currentFood: food || {}
    });
  },

  // 隐藏食材详情
  hideFoodDetail: function() {
    this.setData({
      showDetailModal: false
    });
  },

  // 分类选择
  onCategoryChange: function(e) {
    const index = e.detail.value;
    this.setData({
      selectedCategory: this.data.categories[index]
    });
  },

  // 单位选择
  onUnitChange: function(e) {
    const index = e.detail.value;
    this.setData({
      selectedUnit: this.data.units[index]
    });
  },

  // 日期选择
  onDateChange: function(e) {
    this.setData({
      selectedDate: e.detail.value
    });
  },

  // 添加食材
  addFood: function(e) {
    const formData = e.detail.value;
    
    // 验证表单
    if (!formData.name || !formData.quantity || !this.data.selectedCategory || !this.data.selectedUnit || !this.data.selectedDate) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    
    // 创建新食材
    const newFood = {
      id: Date.now(), // 临时ID
      name: formData.name,
      category: this.data.selectedCategory,
      quantity: parseFloat(formData.quantity),
      unit: this.data.selectedUnit,
      expiryDate: this.data.selectedDate,
      location: formData.location || '',
      imageUrl: '../../images/default-food.png',
      status: 'normal' // 需要根据日期计算实际状态
    };
    
    // 添加到列表
    const foods = [...this.data.foods, newFood];
    this.setData({
      foods: foods,
      showAddModal: false
    });
    
    // 刷新筛选和统计
    this.filterFoods();
    this.updateStats();
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
  },

  // 删除食材
  deleteFood: function() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个食材吗？',
      success: (res) => {
        if (res.confirm) {
          const foods = this.data.foods.filter(food => food.id !== this.data.currentFood.id);
          this.setData({
            foods: foods,
            showDetailModal: false
          });
          
          // 刷新筛选和统计
          this.filterFoods();
          this.updateStats();
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 编辑食材
  editFood: function() {
    // 这里可以跳转到编辑页面或打开编辑模态框
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },

  // 上传图片
  uploadImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (res) => {
        this.setData({
          imagePreview: res.tempFilePaths[0]
        });
      }
    });
  },

  // 拍照
  takePhoto: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        this.setData({
          imagePreview: res.tempFilePaths[0]
        });
      }
    });
  },

  // 识别图片
  recognizeImage: function() {
    wx.showLoading({
      title: '识别中...'
    });
    
    // 模拟OCR识别过程
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '识别成功',
        icon: 'success'
      });
      
      // 这里可以填充表单数据
    }, 1500);
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  }
})